import random

from PyQt5.QtCore import Qt, QCoreApplication
from PyQt5.QtGui import QPainterPath, QPen, QKeySequence, QPainter, QColor
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsPathItem, QGraphicsView, QShortcut, QSlider, QVBoxLayout, QWidget, \
    QWidgetItem, QApplication, QPushButton, QHBoxLayout, QDialog, QColorDialog

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_DaubTouchSetDialog(object):
    def setupUi(self, DaubTouchSetDialog):
        DaubTouchSetDialog.setObjectName("DaubTouchSetDialog")
        DaubTouchSetDialog.resize(480, 500)
        self.verticalLayout = QtWidgets.QVBoxLayout(DaubTouchSetDialog)
        self.verticalLayout.setObjectName("verticalLayout")
        self.btnChangeColor = QtWidgets.QPushButton(DaubTouchSetDialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btnChangeColor.sizePolicy().hasHeightForWidth())
        self.btnChangeColor.setSizePolicy(sizePolicy)
        self.btnChangeColor.setObjectName("btnChangeColor")
        self.verticalLayout.addWidget(self.btnChangeColor)
        self.checkRandomColor = QtWidgets.QCheckBox(DaubTouchSetDialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.checkRandomColor.sizePolicy().hasHeightForWidth())
        self.checkRandomColor.setSizePolicy(sizePolicy)
        self.checkRandomColor.setChecked(True)
        self.checkRandomColor.setObjectName("checkRandomColor")
        self.verticalLayout.addWidget(self.checkRandomColor)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtWidgets.QLabel(DaubTouchSetDialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
        self.label.setSizePolicy(sizePolicy)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.ediPenWidth = QtWidgets.QLineEdit(DaubTouchSetDialog)
        self.ediPenWidth.setObjectName("ediPenWidth")
        self.horizontalLayout.addWidget(self.ediPenWidth)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.hsPenWidth = QtWidgets.QSlider(DaubTouchSetDialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.hsPenWidth.sizePolicy().hasHeightForWidth())
        self.hsPenWidth.setSizePolicy(sizePolicy)
        self.hsPenWidth.setStyleSheet("QSlider::groove{background-color: grey;}\n"
"QSlider::handle{background-color:#05B8CC; border: 3px solid #05B8CC;height: 50px; }\n"
"QSlider::sub-page{background-color:grey; }\n"
"QSlider::add-page{ background-color:white;}")
        self.hsPenWidth.setMaximum(120)
        self.hsPenWidth.setPageStep(10)
        self.hsPenWidth.setOrientation(QtCore.Qt.Horizontal)
        self.hsPenWidth.setObjectName("hsPenWidth")
        self.verticalLayout.addWidget(self.hsPenWidth)
        self.label_2 = QtWidgets.QLabel(DaubTouchSetDialog)
        self.label_2.setObjectName("label_2")
        self.verticalLayout.addWidget(self.label_2)
        self.btnClear = QtWidgets.QPushButton(DaubTouchSetDialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btnClear.sizePolicy().hasHeightForWidth())
        self.btnClear.setSizePolicy(sizePolicy)
        self.btnClear.setObjectName("btnClear")
        self.verticalLayout.addWidget(self.btnClear)
        self.buttonBox = QtWidgets.QDialogButtonBox(DaubTouchSetDialog)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.verticalLayout.addWidget(self.buttonBox)

        self.retranslateUi(DaubTouchSetDialog)
        self.buttonBox.accepted.connect(DaubTouchSetDialog.accept)
        self.buttonBox.rejected.connect(DaubTouchSetDialog.reject)
        QtCore.QMetaObject.connectSlotsByName(DaubTouchSetDialog)

    def retranslateUi(self, DaubTouchSetDialog):
        _translate = QtCore.QCoreApplication.translate
        DaubTouchSetDialog.setWindowTitle(_translate("DaubTouchSetDialog", "Dialog"))
        self.btnChangeColor.setText(_translate("DaubTouchSetDialog", "选择颜色"))
        self.checkRandomColor.setText(_translate("DaubTouchSetDialog", "画线不连续时随机颜色"))
        self.label.setText(_translate("DaubTouchSetDialog", "设置笔记宽度"))
        self.label_2.setText(_translate("DaubTouchSetDialog", "按F11 或者 双击  画面  -> 全屏"))
        self.btnClear.setText(_translate("DaubTouchSetDialog", "清除内容"))

class DaubTouchSetWindow(Ui_DaubTouchSetDialog, QDialog):
    # __timer = QTimer()
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)


class MyScene(QGraphicsScene):  # 自定场景
    pen_color = Qt.black  # 预设笔的颜色
    pen_width = 5  # 预设笔的宽度

    def __init__(self):  # 初始函数
        super(MyScene, self).__init__()  # 实例化QGraphicsScene
        # self.setSceneRect(0, 0, 800, 600)  # 设置场景起始及大小，默认场景是中心为起始，不方便后面的代码

    def mousePressEvent(self, event):  # 重载鼠标事件
        if event.button() == Qt.LeftButton:  # 仅左键事件触发
            self.QGraphicsPath = QGraphicsPathItem()  # 实例QGraphicsPathItem
            self.path1 = QPainterPath()  # 实例路径函数
            my_pen = QPen()  # 实例QPen
            self.path1.moveTo(event.scenePos())  # 路径开始于
            # print('event.scenePos()', event.scenePos())
            my_pen.setColor(self.pen_color)  # 设置颜色
            my_pen.setWidth(self.pen_width)  # 设置宽度
            self.QGraphicsPath.setPen(my_pen)  # 应用笔
            self.addItem(self.QGraphicsPath)  # 场景添加图元

    def mouseMoveEvent(self, event):  # 重载鼠标移动事件
        if event.buttons() & Qt.LeftButton:  # 仅左键时触发，event.button返回notbutton，需event.buttons()判断，这应是对象列表，用&判断
            if self.path1:  # 判断self.path1
                self.path1.lineTo(event.scenePos())  # 移动并连接点
                self.QGraphicsPath.setPath(self.path1)  # self.QGraphicsPath添加路径，如果写在上面的函数，是没线显示的，写在下面则在松键才出现线

    def mouseReleaseEvent(self, event):  # 重载鼠标松开事件
        if event.button() == Qt.LeftButton:  # 判断左键松开
            if self.path1:
                self.path1.closeSubpath()  # 结束路径


class DaubTouchWindow(QGraphicsView):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        # 引入公共程序
        from utils.common import commonProgram
        # 引入配置文件
        self.myConfig = commonProgram.EnableConfigHandler()
        print('GraphicsViewWindow get config Version', self.myConfig.version)

        # 打开设置窗口
        self.daubTouchSetWin = DaubTouchSetWindow()
        self.daubTouchSetWin.show()
        self.daubTouchSetWin.btnClear.clicked.connect(self.clean_all)
        self.daubTouchSetWin.btnChangeColor.clicked.connect(self.ChangeColorFun)
        self.daubTouchSetWin.hsPenWidth.valueChanged.connect(self.ChangePenWidh)
        self.daubTouchSetWin.ediPenWidth.textChanged.connect(self.ChangePenWidhByText)

        # 快捷键
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               双击 或者 F11')

        # 创建场景
        # self.graphicsScene = QGraphicsScene()
        self.graphicsScene = MyScene()
        self.graphicsScene.clearSelection()  # 【清除选择】
        self.setSceneRect(0, 0, self.myConfig.screenLength / 2, self.myConfig.screenWidth / 2)
        self.setScene(self.graphicsScene)
        self.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        self.setRenderHint(QPainter.Antialiasing)  ##设置视图的抗锯齿渲染模式。

        # 隐藏滚动条
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        # 以鼠标所在位置为锚点进行缩放
        self.setTransformationAnchor(self.AnchorUnderMouse)

        # 平滑缩放
        # self.pixmapItem.setTransformationMode(Qt.SmoothTransformation)
        self.setRenderHints(QPainter.Antialiasing |
                            QPainter.SmoothPixmapTransform)

        # 去边框
        # self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        self.setStyleSheet("border-width: 0px; border-style: solid")
        # self.setStyleSheet("border: 0px")

        self.daubTouchSetWin.ediPenWidth.setText(str(self.graphicsScene.pen_width))
        # 随机颜色
        self.colorList = []
        for i in range(3, 256, 4):
            for j in range(3, 256, 4):
                for k in range(3, 256, 4):
                    colorStr = ('#FF' + hex(i)[2:] + hex(j)[2:] + hex(k)[2:])
                    self.colorList.append(colorStr)
            # [Qt.magenta, Qt.darkMagenta, Qt.black, Qt.red, Qt.darkRed, Qt.color0, Qt.color1, Qt.cyan,
            #          Qt.darkCyan,Qt.yellow, Qt.darkYellow, Qt.green, Qt.darkGreen, Qt.blue, Qt.darkBlue,
            #          Qt.lightGray, Qt.gray, Qt.darkGray]

    def ChangePenWidh(self):  # 改变画符宽度，其实应该直接信号槽写临函也可以
        self.graphicsScene.pen_width = self.daubTouchSetWin.hsPenWidth.value()
        self.daubTouchSetWin.ediPenWidth.setText(str(self.daubTouchSetWin.hsPenWidth.value()))

    def ChangePenWidhByText(self):
        try:
            self.daubTouchSetWin.hsPenWidth.setValue(int(self.daubTouchSetWin.ediPenWidth.text()))
            self.graphicsScene.pen_width = self.daubTouchSetWin.hsPenWidth.value()
        except Exception as e:
            pass

    def ChangeColorFun(self):  # 换画笔颜色
        color = QColorDialog.getColor()
        # print('ChangeColorFun', color)
        self.graphicsScene.pen_color = color

    def clean_all(self):  # 清除图元
        # print('clean_all')
        self.graphicsScene.clear()

    def WindowSizeFun(self):
        # print(toStatus)
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'

    def mouseDoubleClickEvent(self, event):
        # point = self.mapToScene(event.pos())
        # item = self.graphicsScene.itemAt(point, QTransform())
        # self.graphicsScene.removeItem(item)
        self.WindowSizeFun()
        super().mouseDoubleClickEvent(event)

    def mouseReleaseEvent(self, event: QtGui.QMouseEvent):
        if self.daubTouchSetWin.checkRandomColor.isChecked():
            self.graphicsScene.pen_color = QColor(random.choice(self.colorList))
        # print('mouseReleaseEvent', event)

    def closeEvent(self, event):
        self.close()
        self.daubTouchSetWin.close()


if __name__ == '__main__':
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    import sys

    app = QApplication(sys.argv)
    MyWin = DaubTouchWindow()
    MyWin.show()
    sys.exit(app.exec_())
